package com.enniswu.weitter.base;

import android.support.annotation.Nullable;
import android.util.Log;

import com.enniswu.weitter.entity.JsonBean;
import com.enniswu.weitter.network.HttpClient;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Response;

public abstract class BaseModel {

    public interface Callback<T> {
        void onFailure(String msg);
        void onSuccess(@Nullable T t);
    }

    @Nullable
    public String catchSessionId(Response response) {
        String cookie = response.header("Set-Cookie");
        if (cookie == null)
            return null;
        return cookie.substring(0 ,cookie.indexOf(";"));
    }

    protected static class HttpCallbackImpl<T> implements okhttp3.Callback {
        protected int code;
        protected Callback<T> back;
        protected Type type;

        public HttpCallbackImpl(Callback<T> back, Type type) {
            this.back = back;
            this.type = type;
        }

        @Nullable
        protected String handleResponse(Response response) throws IOException {
            String string = response.body().string();
            Log.d("回复", string);
            try {
                JSONObject object = new JSONObject(string);
                if (!object.has("code")) {
                    back.onFailure(HttpClient.getErrorMessage());
                    return null;
                }
                code = object.getInt("code");
                if (code != 0) {
                    back.onFailure(HttpClient.getMessage(code));
                    return null;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return string;
        }

        @Override
        public void onFailure(Call call, IOException e) {
            back.onFailure(HttpClient.getFailMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String string = handleResponse(response);
            if (string != null)
                onSuccess(string);
        }

        public void onSuccess(String json) {
            JsonBean<T> jsonBean = new Gson().fromJson(json, type);
            back.onSuccess(jsonBean.getT());
        }
    }
}
